package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.*;
import cn.wolfcode.trip.base.mapper.*;
import cn.wolfcode.trip.base.query.CollectionQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.WishQueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.QPDecoderStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyMapper strategyMapper;
    @Autowired
    private DailyMapper dailyMapper;
    @Autowired
    private WishMapper wishMapper;
    @Autowired
    private LikeMessageMapper likeMessageMapper;
    @Autowired
    private StrategyCommentMapper strategyCommentMapper;
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public void register(User user) {
        String email = user.getEmail();
        User temp = userMapper.selectByEmailAndPassword(email, null);
        if (temp != null) {
            throw new RuntimeException("该邮箱已被注册!");
        }
        user.setHeadImgUrl("/img/user/head.jpg");
        user.setCoverImgUrl("/img/user/bg.jpeg");
        userMapper.insert(user);
    }

    @Override
    public User login(User user) {
        if (StringUtils.hasLength(user.getEmail()) && StringUtils.hasLength(user.getPassword())) {
            User temp = userMapper.selectByEmailAndPassword(user.getEmail(), user.getPassword());
            if (temp != null) {
                //在session中共享登录用户
                UserContext.setCurrentUser(temp);
                return temp;
            }
            throw new RuntimeException("邮箱或密码错误!");
        }
        throw new RuntimeException("邮箱或密码为空!");
    }

    @Override
    public PageInfo<User> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<User> list = userMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void update(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    @Override
    public User selectById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<?> queryForCollections(CollectionQueryObject qo) {
        //获得当前登录的用户id
        Long userId = UserContext.getCurrentUser().getId();
        //判断查询的类型
        int type = qo.getType();
        //游记收藏
        if (type == 1) {
            PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
            List<Travel> list = travelMapper.listForTravel(userId);
            PageInfo<Travel> pageInfo = new PageInfo<>(list);
            return pageInfo;
            //攻略收藏
        } else if (type == 2) {
            PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
            List<StrategyDetail> list = strategyDetailMapper.listForStrategyDetail(userId);
            PageInfo<StrategyDetail> pageInfo = new PageInfo<>(list);
            return pageInfo;
            //日报收藏
        } else {
            PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
            List<Daily> list = dailyMapper.listForDaily(userId);
            PageInfo<Daily> pageInfo = new PageInfo<>(list);
            return pageInfo;
        }

    }

    @Override
    public int getByTravelId(Long travelId) {
        //获得当前登录的用户id
        Long userId = UserContext.getCurrentUser().getId();
        int count = travelMapper.getByTravelId(userId, travelId);
        if (count != 0) {
            return count;
        } else {
            throw new RuntimeException("数据不存在");
        }
    }

    @Override
    public int getBystrategyId(Long strategyId) {
        //获得当前登录的用户id
        Long userId = UserContext.getCurrentUser().getId();
        int count = strategyMapper.getBystrategyId(userId, strategyId);
        if (count != 0) {
            return count;
        } else {
            throw new RuntimeException("数据不存在");
        }

    }

    @Override
    public int getBydailyId(Long dailyId) {
        //获得当前登录的用户id
        Long userId = UserContext.getCurrentUser().getId();
        int count = dailyMapper.getByDailyId(userId, dailyId);
        if (count != 0) {
            return count;
        } else {
            throw new RuntimeException("数据不存在");
        }
    }

    @Override
    public void changeTravelCollection(Long travelId, int type) {
        //获得当前登录的用户id
        Long userId = UserContext.getCurrentUser().getId();
        //判断是添加收藏还是取消收藏
        if (type == 1) {
            //添加收藏
            travelMapper.addCollection(userId, travelId);
        } else {
            //取消收藏
            travelMapper.deleteCollection(userId, travelId);
        }
    }

    @Override
    public void changeStrategyCollection(Long strategyId, int type) {
        //获得当前登录的用户id
        Long userId = UserContext.getCurrentUser().getId();
        //判断是添加收藏还是取消收藏
        if (type == 1) {
            //添加收藏
            strategyMapper.addCollection(userId, strategyId);
        } else {
            //取消收藏
            strategyMapper.deleteCollection(userId, strategyId);
        }
    }

    @Override
    public void changeDailyCollection(Long dailyId, int type) {
        //获得当前登录的用户id
        if(UserContext.getCurrentUser() != null){
            Long userId = UserContext.getCurrentUser().getId();
            //判断是添加收藏还是取消收藏
            if (type == 1) {
                //添加收藏
                dailyMapper.addCollection(userId, dailyId);
            } else {
                //取消收藏
                dailyMapper.deleteCollection(userId, dailyId);
            }
        }

    }

    //取消点赞
    @Override
    public void cancelLike(Long articleId, Integer type) {
        //获取当前用户的id
        //type: 1.游记;2.大攻略;3.日报;4.攻略文章
        Long userId = UserContext.getCurrentUser().getId();
        if (type == 1) {
            userMapper.deleteTravelLikeRelationByUserId(userId, articleId);
        } else if (type == 2) {
            userMapper.deleteStrategyLikeRelationByUserId(userId, articleId);
        } else if (type == 3) {
            userMapper.deleteDailyLikeRelationByUserId(userId, articleId);
        } else if (type == 4) {
            userMapper.deleteStrategyDailyLikeRelationByUserId(userId, articleId);
        }
    }

    //点赞
    @Override
    public void like(Long articleId, Integer type) {
        //获取当前用户的id
        //type: 1.游记;2.大攻略;3.日报;4.攻略文章
        if(UserContext.getCurrentUser() != null){
            Long userId = UserContext.getCurrentUser().getId();
            if (type==1){
                userMapper.insertTravelLikeRelationByUserId(userId, articleId);
                //获取点赞的游记对象
                Travel travel = travelMapper.selectByPrimaryKey(articleId);
                //新建点赞消息并传入相应信息
                LikeMessage likeMessage = new LikeMessage();
                likeMessage.setTravel(travel);
                User user = UserContext.getCurrentUser();
                likeMessage.setUser(user);
                //新增点赞信息对象
                likeMessageMapper.insert(likeMessage);
            }else if (type==2){
                userMapper.insertStrategyLikeRelationByUserId(userId,articleId);
            }else if (type==3){
                userMapper.insertDailyLikeRelationByUserId(userId,articleId);
            }else if (type==4){
                userMapper.insertStrategyDailyLikeRelationByUserId(userId,articleId);
            }
        }

    }

    @Override
    public PageInfo queryLikeMessage(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<LikeMessage> list = likeMessageMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void updateLikeMessageState(List<LikeMessage> list) {
        for (LikeMessage likeMessage : list) {
            likeMessage.setState(true);
            likeMessageMapper.updateState(likeMessage);
        }
    }

    @Override
    public Integer queryTotalLikeNum(Long authorId) {
        return likeMessageMapper.selectTotalUnReadNum(authorId);
    }


    @Override
    public int getFansCount(Long userId) {
        return userMapper.getFansCount(userId);
    }

    @Override
    public int getFocusCount(Long fansId) {
        return userMapper.getFocusCount(fansId);
    }

    @Override
    public int judge(Long beVisitedId, Long currentId) {
        return userMapper.judge(beVisitedId, currentId);
    }

    @Override
    public void addFocus(Long beVisitedId, Long currentId) {
        int count = userMapper.addFocus(beVisitedId, currentId);
        if (count != 1) {
            throw new RuntimeException("关注失败");
        }
    }

    @Override
    public void deleteFocus(Long beVisitedId, Long currentId) {
        int count = userMapper.deleteFocus(beVisitedId, currentId);
        if (count != 1) {
            throw new RuntimeException("取关失败");
        }
    }

    @Override
    public PageInfo<Wish> listForWishes(WishQueryObject qo) {
        //获得当前登录的登录
        Long userId = UserContext.getCurrentUser().getId();
        qo.setUserId(userId);
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Wish> list = wishMapper.listForWishes(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void saveWish(Long strategyId) {
        if (strategyId != null) {
            //获得当前登录用户
            User user = UserContext.getCurrentUser();
            //查询Stragety设置到wish对象中
            Strategy strategy = strategyMapper.selectByPrimaryKey(strategyId);
            //查询该用户是否已经添加单心愿单
            int count = wishMapper.selectByUserIdAndStrategyId(user.getId(), strategyId);
            if (count != 0) {
                throw new RuntimeException("请不要重复添加");
            }
            //创建对象
            Wish wish = new Wish();
            wish.setUser(user);
            wish.setStrategy(strategy);
            wishMapper.insert(wish);
        }
    }

    @Override
    public void deleteWish(Long strategyId) {
        if (strategyId != null) {
            //获得当前登录用户
            Long userId = UserContext.getCurrentUser().getId();
            //插叙该用户是否已经添加单心愿单
            int count = wishMapper.deleteWishByUserIdAndStrategyId(userId, strategyId);
            if (count == 0) {
                throw new RuntimeException("操作失败");
            }
        }
    }

    @Override
    public Integer queryTotalNoticeNum(Long userId) {
        return noticeMapper.queryTotalNoticeNum(userId);
    }

    @Override
    public PageInfo selectNoticeList(Long userId, QueryObject qo) {
        qo.setPageSize(6);
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());

        List<Notice> list = noticeMapper.selectNoticeList(userId, qo);
        return new PageInfo(list);
    }

    @Override
    public void updateNoticeState(Long userId) {
        noticeMapper.updateNoticeState(userId);
    }

    @Override
    public Map selectNoticeState(Long userId) {
        Map map = new HashMap();
        List<Integer> noticeArr = noticeMapper.selectNoticeState(userId);
        map.put("noticeArr", noticeArr);
        return map;
    }

    @Override
    public int getBystrategyDetailId(Long strategyDetailId) {
        //获得当前登录的用户id
        Long userId = UserContext.getCurrentUser().getId();
        int count = strategyDetailMapper.getBystrategyDetailId(userId, strategyDetailId);
        if (count != 0) {
            return count;
        } else {
            throw new RuntimeException("数据不存在");
        }
    }

    @Override
    public void changeStrategyDetailCollection(Long strategyDetailId, int type) {
        Long userId = UserContext.getCurrentUser().getId();
        //判断是添加收藏还是取消收藏
        if (type == 1) {
            //添加收藏
            strategyDetailMapper.addCollection(userId, strategyDetailId);
        } else {
            //取消收藏
            strategyDetailMapper.deleteCollection(userId, strategyDetailId);
        }

    }

    @Override
    public int[] coutForAll(Long beVisitedId) {
        int[] nums = new int[3];
        //查询被访问者的的游记数量
        int travelNum = travelMapper.CountForTravel(beVisitedId);
        nums[0] = travelNum;
        //查询被访问者的点评数量
        int strategyCommentNum = strategyCommentMapper.countForUserId(beVisitedId);
        nums[1] = strategyCommentNum;
        //查询被访问者的心愿数量
        int wishNum = wishMapper.countForUserId(beVisitedId);
        nums[2] = wishNum;
        return nums;
    }

    @Override
    public PageInfo ListByUserIdAndType(QueryObject qo ,Long beVisitedId, int type) {
        //设置userId
        qo.setUserId(beVisitedId);
        //判断type
        if (type == 1) {
            PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
            List<Travel> list =  travelMapper.ListForUserId(qo);
            //查询点赞数遍历赋值进去
            for (Travel travel : list) {
                travel.setLikeNum(travelMapper.queryLikeCountByTravelId(travel.getId()));
            }
            return new PageInfo<>(list);
        }else if(type == 2){
            PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
            List<StrategyComment> list =  strategyCommentMapper.ListForUserId(qo);
            //查询评论数赋值进去
            for (StrategyComment strategyComment : list) {
                strategyComment.setCommentNum(commentMapper.selectForNum(strategyComment.getId(), Comment.MODELSTATE_STRATEGYCOMMENT));
            }
            return new PageInfo<>(list);
        }else{
            PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
            List<Wish> list =  wishMapper.ListForUserId(qo);
            return new PageInfo<>(list);
        }
    }

    @Override
    public PageInfo ListForFocus(QueryObject qo) {
        //获得当前登录对象
        User currentUser = UserContext.getCurrentUser();
        if (currentUser != null) {
            Long id = currentUser.getId();
            //qo.setUserId(id);
            qo.setPageSize(5);
            PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
            List<User> list =  userMapper.ListForFocus(qo);
            return new PageInfo<>(list);
        }
        return null;

    }

    @Override
    public PageInfo ListForFans(QueryObject qo) {
        //获得当前登录对象
        User currentUser = UserContext.getCurrentUser();
        if (currentUser != null) {
            Long id = currentUser.getId();
            //qo.setUserId(id);
            qo.setPageSize(5);
            PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
            List<User> list =  userMapper.ListForFans(qo);
            return new PageInfo<>(list);
        }
        return null;
    }

}
